   //
//  CommodityDetailsVC.m
//  phmall
//
//  Created by admin on 2017/9/17.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "CommodityDetailsVC.h"
#import "ShopInfoModel.h"
#import "GoodsNameView.h"
#import "StoreInfoView.h"
#import "EvaluateView.h"
#import "Orderheader.h"
#import "GoodsQRCode.h"
#import "RecommendView.h"
#import "ActionView.h"
#import "SpecificationView.h"
#import "ConfirmAnOrderVC.h"
#import "DetailsModel.h"
#import "GalleryModel.h"
#import "GoodsModel.h"
#import "NoMoreView.h"
#import "EvaluateModel.h"
#import "FUIImageView.h"
#import "DynamicVC.h"
#import <WebKit/WebKit.h>
#import "OrderModel.h"
#import "ShoppingCartVC.h"
#define SPEC_HEIGHT 500
@interface CommodityDetailsVC ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UIWebViewDelegate,UIScrollViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,RecommendViewDelegate,WKUIDelegate,WKNavigationDelegate,SpecificationViewDelegate,StoreInfoViewDelegate>
{
    UIView *headerView;
    NSString *status;
    StoreInfoView *store;
    EvaluateView *evaluate;
    Orderheader *_headView;
    CGFloat height;
    GoodsNameView *name;
    NSString    *alpha;
    UIImageView *background;
 
    SpecificationView *spec;
    UIBarButtonItem* leftBar;
    UIBarButtonItem* rightBar;
    CGFloat offsetX;
}
@property(strong,nonatomic)UITableView *myTableview;
@property(nonatomic,strong)SDCycleScrollView *scrollView;
@property(nonatomic,strong)UIScrollView *scroll;
@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)DetailsModel *model;
//轮播图数组
@property(nonatomic,strong)NSMutableArray *cycleArry;
@property(nonatomic,strong)NSMutableArray *likeArry;
@property(nonatomic,strong)NSMutableArray *evaluateArray;
//商店信息
@property(nonatomic,strong)ShopInfoModel *shopInfo;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation CommodityDetailsVC
//分享链接
- (void)shareLinkContent{
    FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
    content.contentURL = [NSURL URLWithString:@"http://developers.facebook.com"];
    [FBSDKShareDialog showFromViewController:self
                                 withContent:content
                                    delegate:nil];
}

- (WKWebView *)webView{
    if (!_webView) {
        // js代码

        NSString *jScript =[NSString stringWithFormat:@"window.onload=function()                                                                                                                                                                           {var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');                                                                                                                                                                            meta.setAttribute('content', 'width=device-width');document.getElementsByTagName('head')[0].appendChild(meta);                                                                                                                                                                           var imgs = document.getElementsByTagName('div');for (var i in imgs) {if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx';imgs[i].style.height = 'auto'; } }                                                                                       var imgs = document.getElementsByTagName('h1');for (var i in imgs) {if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx';imgs[i].style.height = 'auto';}}                                                                                       var imgs = document.getElementsByTagName('h2');for (var i in imgs) {if(i<imgs.length-1){ imgs[i].style.maxWidth = '%.0fpx';imgs[i].style.height = 'auto';} }                                                                                       var imgs = document.getElementsByTagName('h3');for (var i in imgs) {if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx';imgs[i].style.height = 'auto';  } }   var imgs = document.getElementsByTagName('h4');for (var i in imgs) {if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx';imgs[i].style.height = 'auto';} }                                                                                                                                                                                  var imgs = document.getElementsByTagName('h5');for (var i in imgs) {if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx'; imgs[i].style.height = 'auto';}}                                                                                                                                                                                 var imgs = document.getElementsByTagName('h6');for (var i in imgs) {if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx';imgs[i].style.height = 'auto';}}                                                                                                                                                                             var imgs = document.getElementsByTagName('table');for(var i in imgs){if(i<imgs.length-1){imgs[i].style.maxWidth ='%.0fpx';imgs[i].style.height = 'auto';}}                                                                                                                                                                               var imgs = document.getElementsByTagName('tr');for(var i in imgs){if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx'; imgs[i].style.height = 'auto';}}                                                                                                                                                                               var imgs = document.getElementsByTagName('td');for(var i in imgs){if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx'; imgs[i].style.height = 'auto';}}                                                                                                                                                                               var imgs = document.getElementsByTagName('p');for(var i in imgs){if(i<imgs.length-1){imgs[i].style.maxWidth = '%.0fpx'; imgs[i].style.height = 'auto';}}                                                                                                                                                                                var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth = '%.0fpx';imgs[i].style.height = 'auto';}}",SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15,SCREEN_WIDTH-15];
//        NSString *jScript =@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);                                                                                                  var imgs = document.getElementsByTagName('img');                                                                                                            for (var i in imgs){imgs[i].style.maxWidth='360';imgs[i].style.height='auto';}                                                                                                    var imgs = document.getElementsByTagName('div');                                                                                                               }";
        //        div，h1,h2,h3,h4,h5,h6,table,tr,td,p,img
        // 根据JS字符串初始化WKUserScript对象
        WKUserScript *script = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        [config.userContentController addUserScript:script];
        
        //初始化偏好设置属性：preferences
        config.preferences = [WKPreferences new];
        //The minimum font size in points default is 0;
        config.preferences.minimumFontSize = 10;
        //是否支持JavaScript
        config.preferences.javaScriptEnabled = YES;
        //不通过用户交互，是否可以打开窗口
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100) configuration:config];
        _webView.UIDelegate =self;
        _webView.navigationDelegate = self;
        // 此处因为高度自适应所以不应该让webview内部可以滚动
        _webView.scrollView.scrollEnabled = NO;
    }
    
    return _webView;
}


-(void)didSelectItemAtIndexPath:(NSString *)uid{
    self.hidesBottomBarWhenPushed=YES;
    CommodityDetailsVC *deta=[[CommodityDetailsVC alloc] init];
    deta.uid=uid;
    [self.navigationController pushViewController:deta animated:YES];
}
-(void)rightBarAction{
    [self loadDataWithInfo];
}
- (void)loadDataWithInfo{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"member_index/get_member_info"];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            self.hidesBottomBarWhenPushed=YES;
            ShoppingCartVC *shop=[[ShoppingCartVC alloc]init];
            shop.BACK=YES;
            [self.navigationController pushViewController:shop animated:YES];
        }else{
            [self userLogout];
        }
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        //[SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}
- (void)analysisDataWithMemberInfoDictionary:(NSDictionary*)dictionary{
    //    UserInfoModel *model = [UserInfoModel yy_modelWithDictionary:dictionary];
    
    YYCache *cache = [YYCache cacheWithName:@"user"];
    [cache setObject:dictionary forKey:@"userInfo"];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //隐藏标签栏
    self.navBarBgAlpha=alpha;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
    //导航栏字体和颜色
    NSMutableDictionary *navDic=@{}.mutableCopy;
    navDic[NSFontAttributeName]=[UIFont systemFontOfSize:20];
    navDic[NSForegroundColorAttributeName]=[UIColor blackColor];
    [self.navigationController.navigationBar setTitleTextAttributes:navDic];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadDataWithGallery];
    self.navBarBgAlpha=alpha=@"0.0";
    leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"详情返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    
    self.navigationItem.leftBarButtonItem=leftBar;
    
    rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"购物车"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
    
    self.navigationItem.rightBarButtonItem=rightBar;
    //表格
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(-STATUS_BAR_HEIGHT-44);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(-(44+self.tabBar_height));
    }];

    self.emptyType=EmptyDataSetNone;
    //底部按钮
    [self getFooterView];
    // Do any additional setup after loading the view.
}
-(void)addSpecificationView{
    background=[UIImageView new];
    background.image=[UIImage imageNamed:@"透明图片"];
    [[UIApplication sharedApplication].keyWindow addSubview:background];
    [background mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.offset(0);
    }];
    background.hidden=YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close)];
    background.userInteractionEnabled=YES;
    [background addGestureRecognizer:tap];
    spec=[[SpecificationView alloc]init];
    spec.delegate=self;
    [[UIApplication sharedApplication].keyWindow  addSubview:spec];
    spec.backgroundColor=[UIColor whiteColor];
    spec.model=self.model;
    [spec mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(SPEC_HEIGHT+self.tabBar_height);
        make.height.offset(SPEC_HEIGHT+self.tabBar_height);
    }];
 
    [spec.myTabV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(spec.mas_bottom).with.offset(-49-self.tabBar_height);
    }];
    [spec.confirm mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(spec).offset(-self.tabBar_height);
    }];
}
-(void)cancel{
    [self close];
}
-(void)close{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        [spec mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.bottom.offset(SPEC_HEIGHT+self.tabBar_height);
            make.height.offset(SPEC_HEIGHT+self.tabBar_height);
        }];
        [spec.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        background.hidden=YES;
    }];
}
-(void)buyAction{
    status=@"buy";
    [UIView animateWithDuration:0.5 animations:^{
        background.hidden=NO;
        [spec mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.bottom.offset(0);
            make.height.offset(SPEC_HEIGHT+self.tabBar_height);
        }];
        [spec.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}
-(void)addCartAction{
    status=@"add";
    [UIView animateWithDuration:0.5 animations:^{
        background.hidden=NO;
        [spec mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.bottom.offset(0);
            make.height.offset(SPEC_HEIGHT+self.tabBar_height);
        }];
        [spec.superview layoutIfNeeded];
    } completion:^(BOOL finished) {

    }];
}
-(void)confirmActionNumber:(NSString *)number attr:(NSString *)attr{
    self.hud =[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"cart/add"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:number forKey:@"goods_num"];
    [parametersDic setValue:self.model.g_uid forKey:@"g_uid"];
    [parametersDic setValue:@"1" forKey:@"setp"];
    NSString *attr_text = [attr stringByReplacingOccurrencesOfString:@"|" withString:@"\\|"];
    if (attr.length==0) {
        [parametersDic setValue:@"" forKey:@"attr"];
        [parametersDic setValue:@"" forKey:@"attr_txt"];
        
    }else{
        [parametersDic setValue:[NSString stringWithFormat:@"%@\\|[0-9]{0,99}\\|[0-9]{0,99}",attr_text] forKey:@"attr"];
        [parametersDic setValue:[NSString stringWithFormat:@"%@|",attr] forKey:@"attr_txt"];
    }
   
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        [self.hud hideAnimated:YES];
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            NSMutableDictionary *data=responseDict[@"data"];
            if ([data[@"status"] isEqualToString:@"1"]) {
                [self close];
                [PublicClass ProgressHUDModeText:Localized(@"添加成功") andTime:2];
               
                if ([status isEqualToString:@"buy"]) {
                    [self settlement:data[@"goods"]];
                }
            }
            if ([data[@"status"] isEqualToString:@"2"]) {
                [PublicClass ProgressHUDModeText:Localized(@"添加失败，购物车已有该商品") andTime:2];
            }
            if ([data[@"status"] isEqualToString:@"-2"]) {
                [PublicClass ProgressHUDModeText:Localized(@"添加失败，库存不足") andTime:2];
            }
        }else{
            [self close];
            [self userLogout];
        }
       
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        self.emptyType=EmptyDataSetNoNetwork;
     
    }];
    
    
//        self.hidesBottomBarWhenPushed=YES;
//        ConfirmAnOrderVC *sear=[[ConfirmAnOrderVC alloc] init];
//        [self.navigationController pushViewController:sear animated:YES];
}

-(void)settlement:(NSMutableDictionary *)goods{
    NSMutableArray *orderArray=[[NSMutableArray alloc]init];

    OrderModel *order=[[OrderModel alloc]init];
    NSMutableArray *goodsArray=[[NSMutableArray alloc]init];
//    NSString *shop_name=[[NSString alloc]init];
//    NSString *shop_id=[[NSString alloc]init];

    GoodsListModel *model=[[GoodsListModel alloc]init];
    model.goods_name=self.model.goods_name;
    model.buy_price=goods[@"cart_price"];
    model.buy_number=goods[@"cart_num"];
    model.goods_attr=goods[@"attr"];
    model.g_uid=goods[@"uid"];
    model.goods_file=self.model.goods_file1;
    [goodsArray addObject:model];
   
    order.goods_list=goodsArray;
    order.shop_name= self.model.shop_list[@"shop_name"];
    order.m_uid= goods[@"supplier_id"];
    order.all_number=[NSString stringWithFormat:@"%lu",(unsigned long)goodsArray.count];
    [orderArray addObject:order];

    self.hidesBottomBarWhenPushed=YES;
    ConfirmAnOrderVC *sear=[[ConfirmAnOrderVC alloc] init];
    sear.orderArray=orderArray;
    [self.navigationController pushViewController:sear animated:YES];
}


-(void)getHeaderView{
    //整体界面
    headerView=[UIView new];
    headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    //轮播图
    self.scrollView = [[SDCycleScrollView alloc] init];
    self.scrollView.autoScrollTimeInterval=5;
    self.scrollView.pageControlDotSize=CGSizeMake(6, 6);
    self.scrollView.pageDotColor=[UIColor blackColor];
    self.scrollView.currentPageDotColor=[UIColor orangeColor];
    self.scrollView.placeholderImage=[UIImage imageNamed:@"图片空白页"];
    [headerView addSubview:self.scrollView];
    self.scrollView.delegate=self;
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView).priorityHigh();
        make.left.equalTo(headerView).priorityHigh();
        make.right.equalTo(headerView).priorityHigh();
        make.height.mas_equalTo(SCREEN_WIDTH).priorityHigh();
    }];
    _scrollView.bannerImageViewContentMode=UIViewContentModeScaleToFill;
    NSMutableArray *cycle=[[NSMutableArray alloc] init];
    if (self.cycleArry.count==0) {
        [cycle addObject:[NSString stringWithFormat:@"%@union/%@",IMGURL,self.model.goods_file1]];
    }else{
        for (GalleryModel *model in self.cycleArry) {
            [cycle addObject:model.imgbig];
        }
    }
    _scrollView.imageURLStringsGroup=cycle;
    
    //商品名称视图
    name=[[GoodsNameView alloc] init];
    [headerView addSubview:name];
    name.model=self.model;
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scrollView.mas_bottom);
        make.left.equalTo(headerView);
        make.width.offset(SCREEN_WIDTH).priorityHigh();
        make.bottom.equalTo(name.sales.mas_bottom).offset(8);
    }];
    [name layoutIfNeeded];
    //商店信息
    store=[[StoreInfoView alloc] init];
    [headerView addSubview:store];
    store.delegate=self;
    store.model=self.model;
    [store mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(name.mas_bottom).with.offset(10);
        make.left.right.equalTo(headerView);
//        make.height.offset(130);
        make.bottom.equalTo(store.enter.mas_bottom).offset(10);
//        make.bottom.equalTo(headerView.mas_bottom).with.offset(-10);
    }];
    [store layoutIfNeeded];
    

    _headView = [[Orderheader alloc]init];
    [headerView addSubview:_headView];
    _headView.backgroundColor=[UIColor whiteColor];
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(store.mas_bottom).with.offset(10);
        make.left.right.equalTo(headerView);
        make.height.offset(40);
    }];
    //    _headView.backgroundColor=[UIColor colorWithHexString:@"#f8fafd"];
    __weak typeof(self) weakSelf = self;
    _headView.itemClickAtIndex = ^(NSInteger index){
        [weakSelf adjustScrollView:index];
    };
    _headView.items = @[Localized(@"商品详情"),Localized(@"商品评价")];
    
    height=0;
    _scroll = [[UIScrollView alloc]init];
    _scroll.bounces = NO;
    _scroll.pagingEnabled = YES;
    _scroll.delegate = self;
    [headerView addSubview:_scroll];
    _scroll.backgroundColor=[UIColor whiteColor];
    _scroll.userInteractionEnabled=NO;
    _scroll.contentSize = CGSizeMake(SCREEN_WIDTH*2, height);
    //
    [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headView.mas_bottom).with.offset(0);
        make.left.right.equalTo(headerView);
        make.height.offset(height);
        //        make.bottom.equalTo(headerView.mas_bottom).with.offset(-10);
    }];
    [_scroll.superview layoutIfNeeded];
    
    //商品详情
    NSString *strUrl = [self.model.goods_main stringByReplacingOccurrencesOfString:@"src=\"/english" withString:[NSString stringWithFormat:@"src=\"%@",IMGURL]];
    NSString *strUrl2 = [strUrl stringByReplacingOccurrencesOfString:@"src=\"/union" withString:[NSString stringWithFormat:@"src=\"%@union",IMGURL]];
//    NSString *strUrl3 = [strUrl2 stringByReplacingOccurrencesOfString:@"style=\"" withString:[NSString stringWithFormat:@"style=\"max-width=%.0fpx\"",SCREEN_WIDTH-15]];
    // 加载html字符串
    if (strUrl2!=nil) {
        [self.webView loadHTMLString:strUrl2 baseURL:nil];
    }
   
//    [self.webView loadHTMLString:@"<p style=\"text-align: center\"><img src=\"http://yunjifreebuy.dlgtech.cn/Uploads/goods/2017/08-22/599bea03e304e.png\" style=\"\" title=\"QQ图片20170822161311.png\"/></p><p style=\"text-align: center\"><img src=\"http://yunjifreebuy.dlgtech.cn/Uploads/goods/2017/08-22/599bea0492b2a.png\" style=\"\" title=\"QQ图片20170822161320.png\"/></p><p style=\"text-align: center\"><img src=\"http://yunjifreebuy.dlgtech.cn/Uploads/goods/2017/08-22/599bea0527579.png\" style=\"\" title=\"QQ图片20170822161323.png\"/></p><p style=\"text-align: center;\"><br/></p>\"" baseURL:nil];
    [_scroll addSubview:self.webView];

    //评论
    evaluate=[[EvaluateView alloc] init];
    evaluate.evaluateArray=self.evaluateArray;
    [_scroll addSubview:evaluate];
    [evaluate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scroll);
        make.left.equalTo(_scroll).with.offset(SCREEN_WIDTH);
        make.width.offset(SCREEN_WIDTH);
        self.evaluateArray.count==0 ?  make.bottom.equalTo(evaluate.line.mas_bottom).offset(0.01) : make.bottom.equalTo(evaluate.enter.mas_bottom).offset(10);
    }];
    [evaluate layoutIfNeeded];

    NoMoreView *noMore=[[NoMoreView alloc]init];
    [headerView addSubview:noMore];

    GoodsQRCode *code=[[GoodsQRCode alloc]init];
    [headerView addSubview:code];
    //    code.backgroundColor=[UIColor redColor];
    [code mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_scroll);
        make.top.equalTo(self.scroll.mas_bottom).offset(10);
        make.height.offset(264);
    }];
    [code creatCIQRCodeImage:self.model.uid];
    
    if (self.likeArry.count!=0) {
        RecommendView *recommend=[[RecommendView alloc]init];
        recommend.delegate=self;
        recommend.listArr=self.likeArry;
        NSInteger number=self.likeArry.count/2;
        NSInteger remainder=self.likeArry.count%2;
        remainder==0 ? number :number++;
        CGFloat height=0;
        if (number!=0) {
            if (iPhone5SE) {
                height=230*number+40+(number-1)*10;
            }else  if (iPhone6_6s) {
                height=252*number+40+(number-1)*10;
            }else  if (iPhone6Plus_6sPlus) {
                height=272*number+40+(number-1)*10;
            }else{
                height=252*number+40+(number-1)*10;
            }
        }
        
        [headerView addSubview:recommend];
        [recommend mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_scroll);
            make.height.offset(height);
            make.top.equalTo(code.mas_bottom).with.offset(0);
        }];
        [recommend layoutIfNeeded];
        
        [noMore mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_scroll);
            make.top.equalTo(recommend.mas_bottom).offset(5);
            make.height.offset(30);
            make.bottom.equalTo(headerView.mas_bottom).with.offset(-10);
        }];
    }else{
        [noMore mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_scroll);
            make.top.equalTo(code.mas_bottom).offset(5);
            make.height.offset(30);
            make.bottom.equalTo(headerView.mas_bottom).with.offset(-10);
        }];
    }
    
    //添加webview前计算一次高度
    CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = headerView.bounds;
    frame.size.height = height;
    headerView.frame = frame;
    [self.myTableview setTableHeaderView:headerView];
    [headerView layoutIfNeeded];
}

// 页面加载完成之后调用 此方法会调用多次
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    __block CGFloat webViewHeight;
    //获取内容实际高度（像素）@"document.getElementById(\"content\").offsetHeight;"
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
        // 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度，看参考资料说是对于加载html字符串的情况下使用后者可以，但如果是和我一样直接加载原站内容使用前者更合适
        //获取页面高度，并重置webview的frame
        webViewHeight = [result doubleValue];
        NSLog(@"%f",webViewHeight);
        height=webViewHeight;
        dispatch_async(dispatch_get_main_queue(), ^{
            _scroll.contentSize = CGSizeMake(SCREEN_WIDTH*2, height);
            //
            [_scroll mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_headView.mas_bottom).with.offset(0);
                make.left.right.equalTo(headerView);
                make.height.offset(height);
                //        make.bottom.equalTo(headerView.mas_bottom).with.offset(-10);
            }];
            [_scroll layoutIfNeeded];
         
            [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_scroll);
                make.left.equalTo(_scroll);
                make.height.offset(height);
                make.width.offset(SCREEN_WIDTH);
            }];
            
            //添加webview前计算一次高度
            CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
            CGRect frame = headerView.bounds;
            frame.size.height = height;
            headerView.frame = frame;
            [self.myTableview setTableHeaderView:headerView];
            [headerView layoutIfNeeded];
        });
    }];
}

- (void)getFooterView{
    //底部背景
    UIView *footerView=[UIView new];
    footerView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:footerView];
    
    [footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-self.tabBar_height);
        make.left.right.offset(0);
        make.height.offset(49);
    }];
    
    //立即购买
    UIButton *purchase=[UIButton buttonWithType:UIButtonTypeCustom];
    [purchase setTitle:Localized(@"立即购买") forState:UIControlStateNormal];
    purchase.backgroundColor=[UIColor colorWithHexString:@"#ff802a"];
    [purchase addTarget:self action:@selector(buyAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:purchase];
    purchase.titleLabel.font=[UIFont systemFontOfSize:15];
    [purchase mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.equalTo(footerView);
        make.width.offset(110);
    }];
    //加入购物车
    UIButton *addCart=[UIButton buttonWithType:UIButtonTypeCustom];
    [addCart setTitle:Localized(@"加入购物车") forState:UIControlStateNormal];
    addCart.backgroundColor=[UIColor colorWithHexString:@"#fed900"];
    [addCart addTarget:self action:@selector(addCartAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:addCart];
    addCart.titleLabel.font=[UIFont systemFontOfSize:15];
    [addCart mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(footerView);
        make.right.equalTo(purchase.mas_left);
        make.width.offset(110);
    }];
    //店铺，客服，收藏
    UIView *back=[[UIView alloc] init];
    [footerView addSubview:back];
    back.backgroundColor=[UIColor whiteColor];
    [back mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(footerView);
        make.right.equalTo(addCart.mas_left);
    }];
    [back layoutIfNeeded];
    //    NSLog(@"%f",back.frame.size.width);
    CGFloat width=back.frame.size.width/3;
    NSArray *image=@[@"店铺",@"客服",@"收藏"];
    NSArray *array=@[Localized(@"店铺"),Localized(@"客服"),Localized(@"收藏")];
    for (int i=0; i<array.count; i++) {
        UIButton *but=[UIButton buttonWithType:UIButtonTypeCustom];
        [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [but setTitle:array[i] forState:UIControlStateNormal];
        but.titleLabel.font=[UIFont systemFontOfSize:10];
        [but setImage:[UIImage imageNamed:image[i]] forState:UIControlStateNormal];
        [back addSubview:but];
        [but mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(back);
            make.width.offset(width);
            make.left.equalTo(back).with.offset(width*i);
        }];
        [but addTarget:self action:@selector(butAction:) forControlEvents:UIControlEventTouchUpInside];
        [but layoutIfNeeded];
        but.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [but layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:0];
    }
    
    UIView *line=[[UIView alloc]init];
    [footerView addSubview:line];
    line.backgroundColor=[UIColor colorWithHexString:@"#ECEBEC"];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.offset(0.5);
    }];
}
-(void)butAction:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:Localized(@"店铺")]) {
        [self goToShop];
    }
}
-(void)goToShop{
    self.hidesBottomBarWhenPushed=YES;
    DynamicVC *dynamic=[[DynamicVC alloc]init];
    NSLog(@"%@",self.model.shop_list[@"shop_name"]);
    dynamic.shop_name= self.model.shop_list[@"shop_name"];
    dynamic.uid=self.model.supplier_id;
    [self.navigationController pushViewController:dynamic animated:YES];
}
#pragma mark-通过点击button来改变scrollview的偏移量
-(void)adjustScrollView:(NSInteger)index
{
    if (index==0) {
        [_scroll mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_headView.mas_bottom).with.offset(0);
            make.left.right.equalTo(headerView);
            make.height.mas_equalTo(height);
        }];
       _scroll.contentSize = CGSizeMake(SCREEN_WIDTH*2, height);
    }else{
        [_scroll mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_headView.mas_bottom).with.offset(0);
            make.left.right.equalTo(headerView);
            make.height.mas_equalTo(evaluate.frame.size.height);
        }];
       _scroll.contentSize = CGSizeMake(SCREEN_WIDTH*2, evaluate.frame.size.height);
    }
    [_scroll layoutIfNeeded];
    CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = headerView.bounds;
    frame.size.height = height;
    headerView.frame = frame;
    [self.myTableview setTableHeaderView:headerView];
    [headerView layoutIfNeeded];
    [UIView animateWithDuration:0.2 animations:^{
        _scroll.contentOffset = CGPointMake(index*_scroll.bounds.size.width, 0);
    }];
}

#pragma mark - tableview代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //总高度
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"newCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;;
    }
    cell.opaque=YES;
    cell.layer.drawsAsynchronously=YES;
    cell.layer.rasterizationScale=[UIScreen mainScreen].scale;
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView==self.myTableview) {
        if (scrollView.contentOffset.y>=0 ) {
            if (scrollView.contentOffset.y<=(STATUS_BAR_HEIGHT+44)) {
                self.navBarBgAlpha=alpha=[NSString stringWithFormat:@"%f",scrollView.contentOffset.y/(STATUS_BAR_HEIGHT+44)];
            }else{
                self.navBarBgAlpha=alpha=@"1.0";
            }
            
            if (scrollView.contentOffset.y<=(44)) {
                self.title=@"";
                [leftBar setImage:[[UIImage imageNamed:@"详情返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
                [rightBar setImage:[[UIImage imageNamed:@"购物车"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
            }else{
                self.title=Localized(@"商品详情");
                [leftBar setImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
                [rightBar setImage:[[UIImage imageNamed:@"购物车黑"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
            }
        
        }else{
            self.title=@"";
            self.navBarBgAlpha=alpha=@"0.0";
            [leftBar setImage:[UIImage imageNamed:@"null"]];
            [rightBar setImage:[UIImage imageNamed:@"null"]];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            return nil;
            break;
        case EmptyDataSetNoNetwork:
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
    
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
    return YES;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
}

#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadDataWithProduct];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text = Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.myTableview.contentOffset = CGPointZero;
}


- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
        _myTableview.emptyDataSetSource = self;
        _myTableview.emptyDataSetDelegate = self;
    }
    return _myTableview;
}
-(NSMutableArray *)likeArry{
    if (!_likeArry) {
        _likeArry=[[NSMutableArray alloc] init];
    }
    return _likeArry;
}
-(NSMutableArray *)evaluateArray{
    if (!_evaluateArray) {
        _evaluateArray=[[NSMutableArray alloc] init];
    }
    return _evaluateArray;
}
-(NSMutableArray *)cycleArry{
    if (!_cycleArry) {
        _cycleArry=[[NSMutableArray alloc] init];
    }
    return _cycleArry;
}

- (void)loadDataWithProduct{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"union/product"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:@"1" forKey:@"setp"];
    [parametersDic setObject:self.uid forKey:@"uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        self.emptyType=EmptyDataSetNoData;
        
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSMutableArray *data=responseDict[@"data"];
                self.model=[DetailsModel yy_modelWithDictionary:data[0]];
            }
            [self loadDataWithLike];
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
    }];
}
- (void)loadDataWithGallery{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"union/product/get_gallery"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:@"1" forKey:@"setp"];
    [parametersDic setObject:self.uid forKey:@"uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        self.emptyType=EmptyDataSetNoData;
        
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            NSMutableArray *data=responseDict[@"data"];
            [self analysisDataWithCycleArray:data];
        }
        [self loadDataWithProduct];
       
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
    }];
}
#pragma mark - 数据转model
- (void)analysisDataWithCycleArray:(NSMutableArray*)array{
    for (NSDictionary *dict in array){
        GalleryModel *model = [GalleryModel yy_modelWithDictionary:dict];
        model.imgbig=[NSString stringWithFormat:@"%@union/%@",IMGURL,model.imgbig];
//        NSLog(@"%@",model.imgbig);
        [self.cycleArry addObject:model];
    }
}

- (void)loadDataWithLike{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"union/product/get_cnxh"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:@"1" forKey:@"setp"];
    [parametersDic setObject:@"supplier_cat" forKey:@"cat"];
    [parametersDic setObject:self.model.supplier_cat forKey:@"cat_uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSMutableArray *data=responseDict[@"data"];
                NSLog(@"%@",data);
                [self analysisDataWithLikeArray:data];
            }
        }
        [self loadDataWithEvaluate];
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
    }];
}
- (void)analysisDataWithLikeArray:(NSMutableArray*)array{
    for (NSDictionary *dict in array){
        GoodsModel *model = [GoodsModel yy_modelWithDictionary:dict];
        [self.likeArry addObject:model];
    }
}

- (void)loadDataWithEvaluate{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"union/product/get_comment"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:@"1" forKey:@"setp"];
    [parametersDic setObject:self.model.uid forKey:@"uid"];
    [parametersDic setObject:self.model.supplier_cat forKey:@"cat_uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSMutableArray *data=responseDict[@"data"];
                [self analysisDataWithEvaluateArray:data];
            }
        }
        [self getHeaderView];
        [self addSpecificationView];
        [self.myTableview reloadData];
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
    }];
}
- (void)analysisDataWithEvaluateArray:(NSMutableArray*)array{
    for (NSDictionary *dict in array){
        EvaluateModel *model = [EvaluateModel yy_modelWithDictionary:dict];
        [self.evaluateArray addObject:model];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
